package proxy.dyn;

import java.lang.reflect.Proxy;

/**
 * @description: 代理服务层  代理对象通过指定不同的代理类来调用不同的实现方法
 * 方式为 通过代理得到一个对象 这个代理的方法通过Proxy.newProxyInstance 统一创建
　* @author 周杨
　* @date 2019/6/13  13:29
**/
class MatchService {
    MatchService(){
        //相当于 new PersonImpl();
        PersonBean joe = getPersonInfo("joe", "male", "running");

        PersonBean ownerProxy = getOwnerProxy(joe);//代理层传入一个对象 获得这个对象的某些方法
        System.out.println("Name is " + ownerProxy.getName());
        System.out.println("Interests is " + ownerProxy.getInterests());
        ownerProxy.setInterests("Bowling");
        System.out.println("Interests is " + ownerProxy.getInterests());
        ownerProxy.setHotOrNotRating(50);
        System.out.println("Rating is " + ownerProxy.getHotOrNotRating());
        ownerProxy.setHotOrNotRating(40);
        System.out.println("Rating is " + ownerProxy.getHotOrNotRating());
        System.out.println("***************************");
        PersonBean nonOwnerProxy = getNonOwnerProxy(joe);
        System.out.println("Name is " + nonOwnerProxy.getName());
        System.out.println("Interests is " + nonOwnerProxy.getInterests());
        nonOwnerProxy.setInterests("haha");
        System.out.println("Interests is " + nonOwnerProxy.getInterests());
        nonOwnerProxy.setHotOrNotRating(60);
        System.out.println("Rating is " + nonOwnerProxy.getHotOrNotRating());
    }

    //以下方法全私有

    //代理层方法 传入一个类对象
    private PersonBean getOwnerProxy(PersonBean person) {
        return (PersonBean) Proxy.newProxyInstance(person.getClass().getClassLoader(),
                person.getClass().getInterfaces(), new OwnerInvocationHandler(person));
    }

    //代理层方法 自己调用自己的方法
    private PersonBean getNonOwnerProxy(PersonBean person){
        return (PersonBean)Proxy.newProxyInstance(person.getClass().getClassLoader(),
                person.getClass().getInterfaces(), new NonOwnerInvocationHandler(person));
    }

    //私有方法 通过bean对象 获取
    private PersonBean getPersonInfo(String name, String gender, String interests) {
        PersonBean person = new PersonBeanImpl();
        person.setName(name);
        person.setGender(gender);
        person.setInterests(interests);
        return person;
    }
}
